/**
 * Company : SIANGKLOM.
 * Created By : Chatree Siangklom
 * Created On : Sep 25, 2013  3:20:51 PM 
 * e-Mail : dr_chatree@hotmail.com
 * Mobile Phone : (+66) 087-921-5115
 * Package Name : com.tis.interfaces.controller.security
 * File Name : UserRegistrationController.java
 * TODO
 */
package com.tis.interfaces.controller.security;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import promis.utility.CommonService;

import com.tis.database.entitys.security.AdUserLogin;
import com.tis.database.entitys.staging.ApplicationLoging;
import com.tis.database.services.security.IAdUserLoginServices;
import com.tis.encryption.AESUrlencrp;
import com.tis.encryption.AESencrp;
import com.tis.interfaces.apps.VIEW_FORM;
import com.tis.interfaces.controller.commons.CommonController;

/**
 * @author Chatree Siangklom of Administrator
 * Date =Sep 25, 2013 : 3:20:51 PM 
 * CreateBy=Chatree Siangklom
 * TODO
 */
@Controller
@RequestMapping(value=UserRegistrationController.url)
public class UserRegistrationController extends CommonController {
	
	private static final Logger logging = LoggerFactory.getLogger(UserRegistrationController.class);
	public static final String url = "/security/user/register";
	public static final String uri = "/security/user/register";
	
	private String Translation(String val) {
		String temp = "";
		if(CommonService.IsNullRString(val).equals("O"))
			temp = "Open";
		else if(CommonService.IsNullRString(val).equals("A"))
			temp = "Approved";
		else if(CommonService.IsNullRString(val).equals("C"))
			temp = "Cancelled";
		
		return temp;
	}
	
	@RequestMapping(value="list")
	public String index(HttpServletRequest request, Model model) throws Exception 
	{
		try {			
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); } catch(Exception e) {e.printStackTrace();}
			
			if(!UserLoginValidation((request)))
				return "redirect:/login";
			
			AdUserLogin adUserLogin = GetAdUserLoginSession(request);			
			if(adUserLogin != null) {				
				if(adUserLogin.getUserLogin().equals("F{||9||}PZtTgA4k5q{||9||}9o6Jzik6w{||4||}{||4||}"))
					return uri + "/list";
			}
			
		}catch(Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			throw e;
		}
		
		return null;
	}
	
	@Autowired IAdUserLoginServices iAdUserLoginServices;
	@RequestMapping(value="users/list/json", method = RequestMethod.GET, headers="accept=application/json")
	@ResponseBody
	public List<UserRegistrationForm> listSearch(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			if(!UserLoginValidation((request))) { response.setStatus(500); return null;}
			
			AdUserLogin adUserLogin = GetAdUserLoginSession(request);			
			if(adUserLogin != null) {				
				if(adUserLogin.getUserLogin().equals("F{||9||}PZtTgA4k5q{||9||}9o6Jzik6w{||4||}{||4||}"))
				{
					List<AdUserLogin> lst = iAdUserLoginServices.findByAll(-1, "N", null, null);
					logging.info("AdUserLogin size =" + CommonService.getSize(lst));
					
					return (CommonService.getSize(lst) > 0) ? ConvertToForm(lst) : null;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
			throw e;
		}
		return null;
	}
	
	/**
	 * 
	 * Date =Oct 1, 2013 : 11:26:28 AM 
	 * CreateBy=Chatree Siangklom
	 * TODO
	 * @param lst
	 * @return
	 * @throws Exception
	 */
	private List<UserRegistrationForm> ConvertToForm(List<AdUserLogin> lst) throws Exception {
		
		if(CommonService.getSize(lst) > 0) {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			List<UserRegistrationForm> newLst = new ArrayList<UserRegistrationForm>();
			for(AdUserLogin value : lst) {
				
				if(CommonService.IsNullRString(value.getUserLogin()).equals("F{||9||}PZtTgA4k5q{||9||}9o6Jzik6w{||4||}{||4||}")) continue;
				
				UserRegistrationForm model = new UserRegistrationForm();
				if(!CommonService.IsNull(value.getUserLogin()))
					model.setUserLogin(AESencrp.decrypt(value.getUserLogin()));
				
				model.setPkId(AESUrlencrp.encrypt(value.getPkId().toString()));
				model.setTitleName(value.getTitleName());
				model.setFirstName(value.getFirstName());
				model.setLastName(value.getLastName());
				model.setExpiredDate(CommonService.ConvertDateTimeToStringDisplay(value.getExpiredDate()));
				model.setStatusText(Translation(value.getStatus()));
				newLst.add(model);
			}
			return newLst;
		}		
		return null;
	}
	
	@RequestMapping(value="create", method=RequestMethod.GET)
	public String PreCreate(HttpServletRequest request, Model model) throws Exception 
	{
		String messageString = "";
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			//Put History 		
			try { UserAccessTime(request, this.toString()); }catch(Exception e) {e.printStackTrace();}
			
			if(!UserLoginValidation((request)))
				return "redirect:/login";
			
			AdUserLogin adUserLogin = GetAdUserLoginSession(request);
			
			if(adUserLogin != null) {
				
				if(adUserLogin.getUserLogin().equals("F{||9||}PZtTgA4k5q{||9||}9o6Jzik6w{||4||}{||4||}"))
				{
					UserRegistrationForm obj = new UserRegistrationForm();
					
					obj.setIsactive("Y");
					obj.setStatus("O");
					obj.setStatusText(Translation("O"));
					
					obj.setCreatedOn(CommonService.ConvertDateToStringDisplay(new Date()));
					obj.setCreatedBy(adUserLogin.getPkId().toString());
					obj.setCreatedByName(Fullname(adUserLogin));
					
					obj.setUpdatedOn(CommonService.ConvertDateToStringDisplay(new Date()));
					obj.setUpdatedBy(adUserLogin.getPkId().toString());
					obj.setUpdatedByName(Fullname(adUserLogin));
					
					obj.setStatue(VIEW_FORM.LIST.toString());
					
					model.addAttribute("ObjectForm", obj);
				}else throw new Exception("Error can't create user please check permission. [request session is null]");
			}else {
				throw new Exception("Error can't create user please check permission. [request session is null]");
			}
		}catch(Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			messageString= "Error :" + e.getMessage();
			throw e; 
		}
		model.addAttribute("message", messageString);
		return uri + "/userregister";
	}
	
	@RequestMapping(value="create", method=RequestMethod.POST)
	public String create(HttpServletRequest request, Model model, @ModelAttribute("ObjectForm") @Valid UserRegistrationForm form, BindingResult result) throws Exception {
		logging.info("create -->"+ RequestMethod.POST.toString());
		String messageString = "";
		try {
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
			if(result.hasErrors())
				return uri + "/userregister";
			
			
			logging.info("Password =" + form.getPassword() + "// Repassword=" + form.getRepassword());
			
			if(CommonService.IsNull(form.getPassword()) || CommonService.IsNull(form.getRepassword())) {
				
				messageString = " Password is empty !!!.";
				model.addAttribute("message", messageString);				
				return uri + "/userregister";
			}else if (!form.getPassword().equals(form.getRepassword())){				
				messageString = " Password does not match !!!.";
				model.addAttribute("message", messageString);
				return uri + "/userregister";
			}
			
			List<AdUserLogin> userList = iAdUserLoginServices.findByUserLogin(CommonService.IsNullRString(AESencrp.encrypt(form.getUserLogin())));
			if(CommonService.getSize(userList) > 0) {
				for(AdUserLogin val : userList)
					logging.info("AdUserLogin exists =" + val.toString());
				
				messageString = form.getUserLogin() + " existing user.";
			}else {
				
				AdUserLogin adUserLogin = new AdUserLogin();
				
				BigDecimal pkId = iAdUserLoginServices.NextSequence("AD_USER_LOGIN");
				logging.info("create pkId =" + pkId);
				
				adUserLogin.setPkId(pkId);
				
				adUserLogin.setIsactive(form.getIsactive());
				adUserLogin.setStatus(form.getStatus());
				
				adUserLogin.setCreatedOn(new Date());
				adUserLogin.setCreatedBy(form.getCreatedBy());
				
				adUserLogin.setUpdatedOn(new Date());
				adUserLogin.setUpdatedBy(form.getUpdatedBy());
				
				adUserLogin.setUserLogin(AESencrp.encrypt(form.getUserLogin()));
				
				if(!CommonService.IsNull(form.getPassword()) && !CommonService.IsNull(form.getRepassword()) && CommonService.IsNullRString(form.getPassword()).equals(CommonService.IsNullRString(form.getRepassword())))
					adUserLogin.setPassword(AESencrp.encrypt(form.getPassword()));				

				adUserLogin.setDescription(form.getDescription());
				adUserLogin.setFirstName(form.getFirstName());
				adUserLogin.setLastName(form.getLastName());
				adUserLogin.setTitleName(form.getTitleName());
				
				adUserLogin.setIsdeleted("N");
				
				if(!CommonService.IsNull(form.getExpiredDate()))
					adUserLogin.setExpiredDate(ConvertStringToDateTime(form.getExpiredDate()));
				
				iAdUserLoginServices.save(adUserLogin);
				
				messageString = "Create user Successfull";
				
			}			
		} catch (Exception e) {
			e.printStackTrace();
			messageString= "Error :" + e.getMessage();
			logging.error(e.getMessage());
			throw e;
		}
		
		model.addAttribute("message", messageString);
		return uri + "/userregister";
	}
	
	@RequestMapping(value="edit", method=RequestMethod.GET)
	public String PreEdit(	@RequestParam(value="pkId", required=true) String pkId,
							Model model,
							HttpServletRequest request) throws Exception {
		String messageString = "";
		try {
			logging.info("update -->" + RequestMethod.GET.toString());
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
			if(!CommonService.IsNull(pkId)) {
				logging.info("pkId =" + pkId);
				pkId = AESUrlencrp.decrypt(pkId);
				logging.info("decrypt pkId =" + pkId);
				AdUserLogin adUserLogin = iAdUserLoginServices.findById(CommonService.ConvertStringToBigDecimal(pkId));
				if(adUserLogin != null) {
					logging.info("adUserLogin delete=" + adUserLogin.toString());
					if(CommonService.IsNullRString(adUserLogin.getIsdeleted()).equals("N") || CommonService.IsNull(adUserLogin.getIsdeleted())) {
					
						UserRegistrationForm obj = new UserRegistrationForm();
						
						obj.setPkId(AESUrlencrp.encrypt(adUserLogin.getPkId().toString()));
						
						obj.setIsactive(adUserLogin.getIsactive());
						obj.setStatus(adUserLogin.getStatus());
						obj.setStatusText(Translation(adUserLogin.getStatus()));						
						
						obj.setCreatedOn(CommonService.ConvertDateToStringDisplay(adUserLogin.getCreatedOn()));
						
						AdUserLogin user = null;
						if(!CommonService.IsNull(adUserLogin.getCreatedBy())) {
							user = iAdUserLoginServices.findById(CommonService.ConvertStringToBigDecimal(adUserLogin.getCreatedBy()));
							obj.setCreatedBy(adUserLogin.getPkId().toString());
							obj.setCreatedByName(Fullname(adUserLogin));
							obj.setUpdatedOn(CommonService.ConvertDateToStringDisplay(new Date()));
						}
						
						if(!CommonService.IsNull(adUserLogin.getUpdatedBy())) {
							user = null;
							user = iAdUserLoginServices.findById(CommonService.ConvertStringToBigDecimal(adUserLogin.getUpdatedBy()));
							obj.setUpdatedBy(user.getPkId().toString());
							obj.setUpdatedByName(Fullname(user));
						}
						
						obj.setUserLogin(AESencrp.decrypt(adUserLogin.getUserLogin()));
						obj.setPassword(AESencrp.decrypt(adUserLogin.getPassword()));
						obj.setRepassword(AESencrp.decrypt(adUserLogin.getPassword()));
						obj.setDescription(adUserLogin.getDescription());
						obj.setFirstName(adUserLogin.getFirstName());
						obj.setLastName(adUserLogin.getLastName());
						obj.setTitleName(adUserLogin.getTitleName());
						obj.setRepassword(adUserLogin.getPassword());
						
						if(!CommonService.IsNull(adUserLogin.getExpiredDate()))
							obj.setExpiredDate(CommonService.ConvertDateToStringDisplay(adUserLogin.getExpiredDate()));
							
						model.addAttribute("ObjectForm", obj);
					}
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			messageString = e.getMessage();
			throw e;
		}
		model.addAttribute("message", messageString);
		return uri + "/edituser";
	}
	
	@RequestMapping(value="edit", method=RequestMethod.POST)
	public String Edit(HttpServletRequest request, Model model, @ModelAttribute("ObjectForm") @Valid UserRegistrationForm form, BindingResult result) throws Exception {
		String messageString = "";
		try {
			logging.info("edit -->" + RequestMethod.POST.toString());
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
			if(result.hasErrors())
				return uri + "/edituser";

				String pkId = AESUrlencrp.decrypt(form.getPkId());
				logging.info("decrypt pkId =" +  pkId);
				AdUserLogin adUserLogin = iAdUserLoginServices.findById(CommonService.ConvertStringToBigDecimal(pkId));
				if(adUserLogin != null) {
					logging.info("adUserLogin edit=" + adUserLogin.toString());
					if(CommonService.IsNullRString(adUserLogin.getIsdeleted()).equals("N") || CommonService.IsNull(adUserLogin.getIsdeleted())) {
						adUserLogin.setUserLogin(AESencrp.encrypt(form.getUserLogin()));
						adUserLogin.setPassword(AESencrp.encrypt(form.getPassword()));
						adUserLogin.setTitleName(form.getTitleName());
						adUserLogin.setFirstName(form.getFirstName());
						adUserLogin.setLastName(form.getLastName());
						adUserLogin.setIsactive(form.getIsactive());
						adUserLogin.setStatus(form.getStatus());
						
						adUserLogin.setExpiredDate(ConvertStringToDateTime(form.getExpiredDate()));
						
						AdUserLogin adUserLoginSession = GetAdUserLoginSession(request);
						
						adUserLogin.setUpdatedBy(adUserLoginSession.getUpdatedBy());
						adUserLogin.setUpdatedOn(new Date());
						
						iAdUserLoginServices.saveOrUpdate(adUserLogin);
						messageString = "Updated Successfull";
					}
				}
			
		} catch (Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			messageString = "Error :" + e.getMessage();
		}
				
		model.addAttribute("message", messageString);
		return uri + "/edituser";
	}
	
	@RequestMapping(value="delete", method=RequestMethod.GET)
	public String Delete(
							@RequestParam(value="pkId", required=true) String pkId,			
							HttpServletRequest request) throws Exception {
		try {
			logging.info("Delete -->" + RequestMethod.GET.toString());
			setCurrentAppsInstanceNo();
			KeepLogs(new ApplicationLoging(getCurrentAppsInstanceNo(), "W", "WELCOME", null, getCurrentAppsInstanceNo()));
			
			if(!UserLoginValidation((request)))
				throw new Exception("Can't Search, Please Login first !!!!");
			
			if(!CommonService.IsNull(pkId)) {
				logging.info("pkId =" + pkId);
				pkId = AESUrlencrp.decrypt(pkId);
				logging.info("decrypt pkId =" + pkId);
				AdUserLogin adUserLogin = iAdUserLoginServices.findById(CommonService.ConvertStringToBigDecimal(pkId));
				if(adUserLogin != null) {
					logging.info("adUserLogin delete=" + adUserLogin.toString());
					if(CommonService.IsNullRString(adUserLogin.getIsdeleted()).equals("N") || CommonService.IsNull(adUserLogin.getIsdeleted())) {
						adUserLogin.setIsdeleted("Y");
						adUserLogin.setDeletedOn(new Date());
						
						AdUserLogin adUserLoginSession = GetAdUserLoginSession(request);						
						if(adUserLoginSession != null) {
							adUserLogin.setDeletedBy(adUserLoginSession.getPkId().toString());
						}		
						
						iAdUserLoginServices.saveOrUpdate(adUserLogin);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logging.error(e.getMessage());
			throw e;
		}
		return "redirect:/"+ UserRegistrationController.url +"/list";
	}
}
